#include "StdAfx.h"
#include "ProxyMgr.h"
#include "Proxy.h"
#include "SessionEventHandler.h"
#include "LoginServer.h"
#include "../../include/GTProto.h"
#include <EndianCast.h>
#include "GateServerRoot.h"

CProxyMgr::CProxyMgr(void)
{
    //for (uint16 i = 1; i <= 4096; i++)
    //{
    //    m_InactiveIds.push_back(i);
    //}
}


CProxyMgr::~CProxyMgr(void)
{
}

CProxy * CProxyMgr::CreateProxy(CSessionEventHandler * pCliSessionEventHandler)
{
    CProxy * pProxy = new CProxy( 
        pCliSessionEventHandler);
    m_Proxies[pProxy->GetID()] = pProxy;
    GT_USER_COUNT_NTF_PKG pkg;
    pkg.count = htons(m_Proxies.size());
    pkg.port = htons(GateServerRoot::Instance()->GetListenerPort());
    CLoginServer::Instance()->Send(GT_USER_COUNT_NTF_ID, &pkg, sizeof(pkg));
    return pProxy;
}

//uint16 CProxyMgr::_FetchID()
//{
//    uint16 result = m_InactiveIds.front();
//    m_InactiveIds.pop_front();
//    return result;
//}

void CProxyMgr::DestroyProxy( CProxy * pProxy )
{
    //m_InactiveIds.push_back(pProxy->GetID());
    m_Proxies.erase(pProxy->GetID());
    delete pProxy;

    GT_USER_COUNT_NTF_PKG pkg;
    pkg.count = htons(m_Proxies.size());
    pkg.port = htons(GateServerRoot::Instance()->GetListenerPort());
    CLoginServer::Instance()->Send(GT_USER_COUNT_NTF_ID, &pkg, sizeof(pkg));
}

CProxy * CProxyMgr::Find( uint64 nSocketPair )
{
    TProxyContainer::iterator i = m_Proxies.find(nSocketPair);
    if (i != m_Proxies.end())
        return i->second;
    return NULL;
}

CProxy * CProxyMgr::Find( uint32 nIPAddr, uint16 port )
{
    return Find(MAKEQWORD(nIPAddr, port));
}

uint16 CProxyMgr::GetProxyCount()
{
    return m_Proxies.size();
}


